#include "database.h"

//数据库初始化(建立连接)
void db_init(){
    conn = mysql_init(NULL);

    MYSQL * ret = mysql_real_connect(conn,host,user,passwd,db,0,NULL,0);
    if(NULL == ret)
        error_log("mysql_init::mysql_real_connect");
}
//数据库查询
MYSQL_RES * db_query(const char * sql){
    //查询
    int ret = mysql_query(conn,sql);
    if(0 != ret){
        error_log("db_query::mysql_query");
        error_log(mysql_error(conn));
    }
    //获取结果
    MYSQL_RES * result = mysql_store_result(conn);
    if(NULL == result){
        error_log("db_query::mysql_store_result");
        error_log(mysql_error(conn));
    }
    return result;
    /*int rows = mysql_num_rows(result);
    int cols = mysql_num_fields(result);
    char * retval = (char *)calloc(rows*cols,DB_UNIT_SIZE);
    MYSQL_ROW row;
    while(NULL!=(row = mysql_fetch_row(result))){
        int k = 0;
        for(int i = 0; i < cols; i++){
            retval[k++] = row[i];
        }
    } */
}
//查询用户名是否存在
int query_username(const char * name){
    const char sql[100] = {0};
    sprintf(sql,"select username from user "
"where username = %s",name);
    MYSQL_RES * res = db_query(sql);
    MYSQL_ROW row = mysql_fetch_row(res);
    if(NULL ==  row[0])
        return 0;
    else
        return 1;    
}
//注册用户信息
int db_user_reg(const char * username,const char * salt,const char * passwd){
    const char insertsql[1024] = {0};
    sprintf(insertsql,"insert into user(username,salt,cryptpassword,pwd) "
"values('%s','%s','%s','%s')",username,salt,passwd,username);
    int ret = mysql_real_query(conn,insertsql,strlen(insertsql));
    if(0 != ret){
        error_log("register_user::mysql_real_query");
        return 0;
    }
    return 1;
}
//数据库关闭
void db_close(){
    mysql_close(conn);
}